package com.csii.modules.online.cgform.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csii.autocode.utils.DbReadTableUtil;
import com.csii.core.api.Result;
import com.csii.core.constant.enums.CgformEnum;
import com.csii.core.system.query.QueryGenerator;
import com.csii.core.util.oConvertUtils;
import com.csii.modules.online.cgform.entity.OnlCgformEnhanceJava;
import com.csii.modules.online.cgform.entity.OnlCgformEnhanceJs;
import com.csii.modules.online.cgform.entity.OnlCgformEnhanceSql;
import com.csii.modules.online.cgform.entity.OnlCgformHead;
import com.csii.modules.online.cgform.mapper.OnlCgformEnhanceJavaMapper;
import com.csii.modules.online.cgform.service.IOnlCgformHeadService;
import com.csii.modules.online.cgform.util.CgformSqlUtil;
import com.csii.modules.online.config.exception.DBException;
import com.csii.modules.system.entity.SysDataSource;
import com.csii.modules.system.service.ISysDataSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Pattern;

@RestController("onlCgformHeadController")
@RequestMapping({"/online/cgform/head"})
public class CgformHeadController {
	private static final Logger log = LoggerFactory.getLogger(CgformHeadController.class);
	@Autowired
	private IOnlCgformHeadService onlCgformHeadService;
	@Autowired
	private OnlCgformEnhanceJavaMapper onlCgformEnhanceJavaMapper;
	@Autowired
	private ISysDataSourceService sysDataSourceService;
	private static List<String> strlist = null;
	@Autowired
	ResourceLoader resourceLoader;
	/**
	 * 分页列表
	 *
	 * @param cgformHead
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return result
	 */
	@GetMapping({"/list"})
	public Result<IPage<OnlCgformHead>> list(OnlCgformHead cgformHead, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		Result result = new Result();
		QueryWrapper wrapper = QueryGenerator.initQueryWrapper(cgformHead, req.getParameterMap());
		Page page = new Page((long) pageNo, (long) pageSize);
		IPage iPage = this.onlCgformHeadService.page(page, wrapper);
		if (cgformHead.getCopyType() != null && cgformHead.getCopyType() == 0) {
			this.onlCgformHeadService.initCopyState(iPage.getRecords());
		}

		result.setSuccess(true);
		result.setResult(iPage);
		return result;
	}

	/**
	 * 添加
	 *
	 * @param onlCgformHead
	 * @return result
	 */
	@PostMapping({"/add"})
	public Result<OnlCgformHead> add(@RequestBody OnlCgformHead onlCgformHead) {
		Result result = new Result();

		try {
			this.onlCgformHeadService.save(onlCgformHead);
			result.success("添加成功！");
		} catch (Exception var4) {
			log.error(var4.getMessage(), var4);
			result.error500("操作失败");
		}

		return result;
	}

	/**
	 * 查询后修改
	 *
	 * @param onlCgformHead
	 * @return
	 */
	@PutMapping({"/edit"})
	public Result<OnlCgformHead> edit(@RequestBody OnlCgformHead onlCgformHead) {
		Result result = new Result();
		OnlCgformHead one = (OnlCgformHead) this.onlCgformHeadService.getById(onlCgformHead.getId());
		if (one == null) {
			result.error500("未找到对应实体");
		} else {
			boolean var4 = this.onlCgformHeadService.updateById(onlCgformHead);
			if (var4) {
				result.success("修改成功!");
			}
		}

		return result;
	}

	/**
	 * 删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping({"/delete"})
	public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		try {
			this.onlCgformHeadService.deleteRecordAndTable(id);
		} catch (DBException dbe) {
			return Result.error("删除失败" + dbe.getMessage());
		} catch (SQLException sqle) {
			return Result.error("删除失败" + sqle.getMessage());
		}

		return Result.ok("删除成功!");
	}

	/**
	 * 移除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping({"/removeRecord"})
	public Result<?> removeRecord(@RequestParam(name = "id", required = true) String id) {
		try {
			this.onlCgformHeadService.deleteRecord(id);
		} catch (DBException var3) {
			return Result.error("移除失败" + var3.getMessage());
		} catch (SQLException var4) {
			return Result.error("移除失败" + var4.getMessage());
		}

		return Result.ok("移除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @param flag 删除标记
	 * @return
	 */
	@DeleteMapping({"/deleteBatch"})
	public Result<OnlCgformHead> deleteBatch(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "flag") String flag) {
		Result result = new Result();
		if (ids != null && !"".equals(ids.trim())) {
			this.onlCgformHeadService.deleteBatch(ids, flag);
			result.success("删除成功!");
		} else {
			result.error500("参数不识别！");
		}

		return result;
	}

	/**
	 * id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping({"/queryById"})
	public Result<OnlCgformHead> queryById(@RequestParam(name = "id", required = true) String id) {
		Result res = new Result();
		OnlCgformHead one = (OnlCgformHead) this.onlCgformHeadService.getById(id);
		if (one == null) {
			res.error500("未找到对应实体");
		} else {
			res.setResult(one);
			res.setSuccess(true);
		}

		return res;
	}

	/**
	 * 表名称查询
	 *
	 * @param tableNames
	 * @return
	 */
	@GetMapping({"/queryByTableNames"})
	public Result<List<OnlCgformHead>> queryByTableNames(@RequestParam(name = "tableNames", required = true) String tableNames) {
		LambdaQueryWrapper<OnlCgformHead> wrapper = new LambdaQueryWrapper();
		String[] strings = tableNames.split(",");
		wrapper.in(OnlCgformHead::getTableName, Arrays.asList(strings));
		List list = this.onlCgformHeadService.list(wrapper);
		return list == null ? Result.error("未找到对应实体") : Result.ok(list);
	}

	/**
	 * 保存
	 *
	 * @param code
	 * @param obj
	 * @return
	 */
	@PostMapping({"/enhanceJs/{code}"})
	public Result<?> enhanceJsSave(@PathVariable("code") String code, @RequestBody OnlCgformEnhanceJs obj) {
		try {
			obj.setCgformHeadId(code);
			this.onlCgformHeadService.saveEnhance(obj);
			return Result.ok("保存成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("保存失败!");
		}
	}

	/**
	 * 查询
	 *
	 * @param code
	 * @param req
	 * @return
	 */
	@GetMapping({"/enhanceJs/{code}"})
	public Result<OnlCgformEnhanceJs> enhanceJsView(@PathVariable("code") String code, HttpServletRequest req) {
		try {
			String type = req.getParameter("type");
			OnlCgformEnhanceJs one = this.onlCgformHeadService.queryEnhance(code, type);
			return one == null ? Result.error("查询为空") : Result.ok(one);
		} catch (Exception var5) {
			log.error(var5.getMessage(), var5);
			return Result.error("查询失败!");
		}
	}

	/**
	 * 编辑保存
	 *
	 * @param code
	 * @param obj
	 * @return
	 */
	@PutMapping({"/enhanceJs/{code}"})
	public Result<?> enhanceJsEdit(@PathVariable("code") String code, @RequestBody OnlCgformEnhanceJs obj) {
		try {
			obj.setCgformHeadId(code);
			this.onlCgformHeadService.editEnhance(obj);
			return Result.ok("保存成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("保存失败!");
		}
	}

	/**
	 * @param formId
	 * @param req
	 * @return
	 */
	@GetMapping({"/enhanceButton/{formId}"})
	public Result<?> enhanceButtonView(@PathVariable("formId") String formId, HttpServletRequest req) {
		try {
			List list = this.onlCgformHeadService.queryButtonList(formId);
			return list != null && list.size() != 0 ? Result.ok(list) : Result.error("查询为空");
		} catch (Exception var4) {
			log.error(var4.getMessage(), var4);
			return Result.error("查询失败!");
		}
	}

	@PostMapping({"/enhanceSql/{formId}"})
	public Result<?> enhanceSqlSave(@PathVariable("formId") String formId, @RequestBody OnlCgformEnhanceSql obj) {
		try {
			obj.setCgformHeadId(formId);
			this.onlCgformHeadService.saveEnhance(obj);
			return Result.ok("保存成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("保存失败!");
		}
	}

	@GetMapping({"/enhanceSql/{formId}"})
	public Result<OnlCgformEnhanceSql> enhanceSqlView(@PathVariable("formId") String formId, HttpServletRequest req) {
		try {
			String buttonCode = req.getParameter("buttonCode");
			OnlCgformEnhanceSql one = this.onlCgformHeadService.queryEnhanceSql(formId, buttonCode);
			return one == null ? Result.error("查询为空") : Result.ok(one);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("查询失败!");
		}
	}

	@PutMapping({"/enhanceSql/{formId}"})
	public Result<?> enhanceSqlEdit(@PathVariable("formId") String formId, @RequestBody OnlCgformEnhanceSql obj) {
		try {
			obj.setCgformHeadId(formId);
			this.onlCgformHeadService.editEnhance(obj);
			return Result.ok("保存成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("保存失败!");
		}
	}

	@PostMapping({"/enhanceJava/{formId}"})
	public Result<?> enhanceJava(@PathVariable("formId") String formId, @RequestBody OnlCgformEnhanceJava obj) {
		try {
			if (!CgformSqlUtil.validate(obj)) {
				return Result.error("类实例化失败，请检查!");
			} else {
				obj.setCgformHeadId(formId);
				if (this.onlCgformHeadService.checkOnlyEnhance(obj)) {
					this.onlCgformHeadService.saveEnhance(obj);
					return Result.ok("保存成功!");
				} else {
					return Result.error("保存失败,数据不唯一!");
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("保存失败!");
		}
	}

	@GetMapping({"/enhanceJava/{formId}"})
	public Result<?> enhanceJavaByFormId(@PathVariable("formId") String formId, OnlCgformEnhanceJava obj) {
		try {
			obj.setCgformHeadId(formId);
			OnlCgformEnhanceJava one = this.onlCgformHeadService.queryEnhanceJava(obj);
			if (one == null) {
				obj.setCgJavaValue((String) null);
				return Result.ok(obj);
			} else {
				return Result.ok(one);
			}
		} catch (Exception var4) {
			log.error(var4.getMessage(), var4);
			return Result.error("查询失败!");
		}
	}

	@GetMapping({"/enhanceJavaByButtonCode/{formId}"})
	public Result<?> c(@PathVariable("formId") String var1, OnlCgformEnhanceJava var2) {
		try {
			LambdaQueryWrapper<OnlCgformEnhanceJava> var3 = new LambdaQueryWrapper();
			var3.eq(OnlCgformEnhanceJava::getButtonCode, var2.getButtonCode());
			var3.eq(OnlCgformEnhanceJava::getCgformHeadId, var1);
			OnlCgformEnhanceJava var4 = (OnlCgformEnhanceJava) this.onlCgformEnhanceJavaMapper.selectOne(var3);
			if (var4 == null) {
				return Result.error("查询为空");
			} else {
				log.info("---------enhanceJavaByButtonCode-----------" + var4.toString());
				return Result.ok(var4);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("查询失败!");
		}
	}

	@PutMapping({"/enhanceJava/{formId}"})
	public Result<?> enhanceJavaPut(@PathVariable("formId") String formId, @RequestBody OnlCgformEnhanceJava obj) {
		try {
			if (!CgformSqlUtil.validate(obj)) {
				return Result.error("类实例化失败，请检查!");
			} else {
				obj.setCgformHeadId(formId);
				if (this.onlCgformHeadService.checkOnlyEnhance(obj)) {
					this.onlCgformHeadService.editEnhance(obj);
					return Result.ok("保存成功!");
				} else {
					return Result.error("保存失败,数据不唯一!");
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("保存失败!");
		}
	}

	@GetMapping({"/queryTables"})
	public Result<?> queryTables(@RequestParam(name = "tableName", required = false) String tableName, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		SysDataSource dataSource= sysDataSourceService.getUseDataSource();
		if(dataSource==null)
			return Result.ok();
		List dataBaseTables;
		try {
			dataBaseTables = DbReadTableUtil.getTableName(dataSource.getDbType(),dataSource.getDbName(),dataSource.getDbUrl(),dataSource.getDbUsername(),dataSource.getDbPassword());
		} catch (SQLException var12) {
			log.error(var12.getMessage(), var12);
			return Result.error("同步失败，未获取数据库表信息");
		}
		CgformSqlUtil.sort(dataBaseTables);
		List onlineTables = this.onlCgformHeadService.queryOnlinetables();
		//本类方法
		this.getExcludeTable();
		dataBaseTables.removeAll(onlineTables);
		ArrayList var8 = new ArrayList();
		Iterator iterator = dataBaseTables.iterator();
		while (iterator.hasNext()) {
			String var10 = (String) iterator.next();
			if (!this.swich(var10)) {
				HashMap var11 = new HashMap();
				var11.put("id", var10);
				var8.add(var11);
			}
		}
		return Result.ok(var8);
	}

	@PostMapping({"/transTables/{tbnames}"})
	public Result<?> transTables(@PathVariable("tbnames") String tbnames) {
		SysDataSource dataSource= sysDataSourceService.getUseDataSource();
		if (oConvertUtils.isEmpty(tbnames)) {
			return Result.error("未识别的表名信息");
		} else {
			String[] tbnameArray = tbnames.split(",");

			for (int i = 0; i < tbnameArray.length; ++i) {
				if (oConvertUtils.isNotEmpty(tbnameArray[i])) {
					int var6 = this.onlCgformHeadService.count(Wrappers.lambdaQuery(OnlCgformHead.class).eq(OnlCgformHead::getTableName, tbnameArray[i]));
					if (var6 <= 0) {
						log.info("[IP] [online数据库导入表]   --表名：" + tbnameArray[i]);
						this.onlCgformHeadService.saveDbTable2Online(dataSource,tbnameArray[i]);
					}
				}
			}
			return Result.ok("同步完成!");
		}
	}

	@GetMapping({"/rootFile"})
	public Result<?> rootFile() {
		JSONArray jsonArray = new JSONArray();
		File[] files = File.listRoots();
		//File[] var3 = files;
		int length = files.length;

		for (int i = 0; i < length; ++i) {
			File file = files[i];
			JSONObject object = new JSONObject();
			if (file.isDirectory()) {
				object.put("key", file.getAbsolutePath());
				object.put("title", file.getPath());
				object.put("opened", false);
				JSONObject var8 = new JSONObject();
				var8.put("icon", "custom");
				object.put("scopedSlots", var8);
				object.put("isLeaf", file.listFiles() == null || file.listFiles().length == 0);
			}

			jsonArray.add(object);
		}

		return Result.ok(jsonArray);
	}

	/**
	 * 代理扫描路径遍历-漏洞修复
	 */
	private static Pattern FilePattern =  Pattern.compile("[\\\\/:*?\"<>|]");
	public static String fileNameFilter(String str){
		return str==null?null:FilePattern.matcher(str).replaceAll("");
	}

	@GetMapping({"/fileTree"})
	public Result<?> fileTree(@RequestParam(name = "parentPath", required = true) String parentPath) {
		JSONArray jsonArray = new JSONArray();

		parentPath = fileNameFilter(parentPath);
		File parent = new File(parentPath);

		File[] files = parent.listFiles();
		int length = files.length;

		for (int i = 0; i < length; ++i) {
			File file = files[i];
			if (file.isDirectory() && oConvertUtils.isNotEmpty(file.getPath())) {
				JSONObject object = new JSONObject();
				System.out.println(file.getPath());
				object.put("key", file.getAbsolutePath());
				object.put("title", file.getPath().substring(file.getPath().lastIndexOf(File.separator) + 1));
				object.put("isLeaf", file.listFiles() == null || file.listFiles().length == 0);
				object.put("opened", false);
				JSONObject chird = new JSONObject();
				chird.put("icon", "custom");
				object.put("scopedSlots", chird);
				jsonArray.add(object);
			}
		}

		return Result.ok(jsonArray);
	}

	@GetMapping({"/tableInfo"})
	public Result<?> tableInfo(@RequestParam(name = "code", required = true) String code) {
		OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
		if (onlCgformHead == null) {
			return Result.error("未找到对应实体");
		} else {
			HashMap map = new HashMap();
			map.put("main", onlCgformHead);
			if (onlCgformHead.getTableType() == 2) {
				String tableStr = onlCgformHead.getSubTableStr();
				if (oConvertUtils.isNotEmpty(tableStr)) {
					ArrayList list = new ArrayList();
					String[] strings = tableStr.split(",");
					int length = strings.length;

					for (int i = 0; i < length; ++i) {
						String s = strings[i];
						LambdaQueryWrapper<OnlCgformHead> wrapper = new LambdaQueryWrapper();
						wrapper.eq(OnlCgformHead::getTableName, s);
						OnlCgformHead one = (OnlCgformHead) this.onlCgformHeadService.getOne(wrapper);
						list.add(one);
					}

					Collections.sort(list, new Comparator<OnlCgformHead>() {
						public int compare(OnlCgformHead var1, OnlCgformHead var2) {
							Integer var3 = var1.getTabOrderNum();
							if (var3 == null) {
								var3 = 0;
							}

							Integer var4 = var2.getTabOrderNum();
							if (var4 == null) {
								var4 = 0;
							}

							return var3.compareTo(var4);
						}
					});
					map.put("sub", list);
				}
			}

			Integer var13 = onlCgformHead.getTableType();
			if ("Y".equals(onlCgformHead.getIsTree())) {
				var13 = 3;
			}

			List var14 = CgformEnum.getJspModelList(var13);
			map.put("jspModeList", var14);
			map.put("projectPath", com.csii.autocode.config.ReadConfig.getProjectPath());
			return Result.ok(map);
		}
	}

	@PostMapping({"/copyOnline"})
	public Result<?> copyOnline(@RequestParam(name = "code", required = true) String code) {
		try {
			OnlCgformHead one = (OnlCgformHead) this.onlCgformHeadService.getById(code);
			if (one == null) {
				return Result.error("未找到对应实体");
			}

			this.onlCgformHeadService.copyOnlineTableConfig(one);
		} catch (Exception var3) {
			var3.printStackTrace();
		}

		return Result.ok();
	}

	private boolean swich(String var1) {
		Iterator var2 = strlist.iterator();

		String var3;
		do {
			if (!var2.hasNext()) {
				return false;
			}

			var3 = (String) var2.next();
		} while (!var1.startsWith(var3) && !var1.startsWith(var3.toUpperCase()));

		return true;
	}

	private void getExcludeTable() {
		if (strlist == null) {
			Resource var1 = this.resourceLoader.getResource("classpath:auto-code" + File.separator + "autocode_config.properties");
			InputStream var2 = null;

			try {
				var2 = var1.getInputStream();
				Properties var3 = new Properties();
				var3.load(var2);
				String var4 = var3.getProperty("exclude_table");
				if (var4 != null) {
					strlist = Arrays.asList(var4.split(","));
				}else {
					strlist = new ArrayList<>();
				}
			} catch (IOException e) {
				log.error(e.getMessage(),e);
			} finally {
				if (var2 != null) {
					try {
						var2.close();
					} catch (IOException e) {
						log.error(e.getMessage(),e);
					}
				}

			}
		}

	}
}
